<?php

namespace App\Http\Controllers\platform;

use App\Http\Controllers\Controller;
use App\Http\Services\jwtAuth;
use App\Models\Personal;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;

class PersonalController extends Controller
{
    public function index(Request $Request)
    {
        $data = [];
        return response()->json(['code' => '200', 'data' => $data]);
    }

    public function session_key(Request $Request)
    {
        $data = [];
        $appid = 'wxcc0ceff93a724fec'; // 替换成你的小程序appid
        $appsecret = 'e481903ee63d7a7adb004b96968f3205'; // 替换成你的小程序appsecret
        $code = $Request->code; // 从前端接收到的code

        $url = "https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appsecret}&js_code={$code}&grant_type=authorization_code";
        $response = file_get_contents($url);
        $result = json_decode($response, true);

        if (isset($result['session_key']) && isset($result['openid'])) {
            // 成功获取到session_key和openid
            $sessionKey = $result['session_key'];
            $openId = $result['openid'];
            return response()->json(['code' => '200', 'data' => $sessionKey, 'openId' => $openId]);
        } else {
        // 处理错误情况
            return response()->json(['code' => '500', 'msg' => $result]);
        }
        return response()->json(['code' => '200', 'data' => $data]);
    }

    public function update(Request $Request)
    {
        $user = Personal::find($Request->uid);
        $user->passwd = password_hash($Request->password,PASSWORD_DEFAULT);
        $user->head_img = $Request->head_img;
        $user->update_time = time();
        $user->save();
        return response()->json(['code' => '200']);
    }


    public function getPhoneNumber(Request $Request)
    {
        $appid = 'wxcc0ceff93a724fec'; // 替换成你的小程序appid
        $appsecret = 'e481903ee63d7a7adb004b96968f3205'; // 替换成你的小程序appsecret
        $iv = $Request->iv;
        $encryptedData = $Request->encryptedData;
        $sessionKey = $Request->sessionKey;
        $code = $Request->code;

        return $this->decryptPhoneNumber($appid, $sessionKey, $iv, $encryptedData,$code);
    }

    public function decryptPhoneNumber($appid, $sessionKey, $iv, $encryptedData,$code) {
        $appsecret = 'e481903ee63d7a7adb004b96968f3205'; // 替换成你的小程序appsecret
        $accessToken = $this->getAccessToken($appid, $appsecret);

        // 调用微信解密接口（注意：这里使用的是微信提供的业务数据接口，不是之前的jscode2session接口）
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token={$accessToken}";
        $response = Http::post($url, [
            'code' => $code,
            // 'encrypted_data' => $encryptedData,
            // 'iv' => $iv,
            // 'session_key' => $sessionKey
        ]);

        $data = $response->json();
        
        if ($data['errcode'] != 0) {
            return response()->json(['code' => $data['errcode'], 'data' => $data['errmsg']]);
        }
        //判断用户是否存在
        $user = Personal::where('tell',$data['phone_info']['phoneNumber'])->first();
        $is = true;
        if(!$user){
            $user = new Personal();
            $user->es_id = 2097;
            $user->tell = $data['phone_info']['phoneNumber'];
            $user->name = '微信用户';
            $user->status = 1;
            $user->passwd = password_hash(123456,PASSWORD_DEFAULT);
            $user->create_time = time();
            $user->update_time = time();
            $user->save();
            $is = false;
        }

        return response()->json(['code' => 200, 'data' => $user,'is' => $is]);
        
    }
    
    public function getAccessToken($appid, $appsecret) {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appid}&secret={$appsecret}";
        $response = Http::get($url);
        $data = $response->json();
        return $data['access_token'];
    }
    
}
